import storageAPI from '@/api/storage'

// 默认AI配置
const DEFAULT_AI_CONFIG = {
  apiUrl: 'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
  modelName: 'doubao-seed-1-6-flash-250615',
  apiKey: ''
}

/**
 * 获取AI模型配置
 * @returns {Promise<Object>} AI配置对象
 */
export async function getAiConfig() {
  try {
    const config = await storageAPI.getItem('aiModelConfig', {})
    
    // 确保config是对象类型
    const configObj = typeof config === 'string' ? JSON.parse(config) : (config || {})
    
    return {
      apiUrl: (configObj.apiUrl || DEFAULT_AI_CONFIG.apiUrl).trim().replace(/[`]/g, ''),
      modelName: (configObj.modelName || DEFAULT_AI_CONFIG.modelName).trim(),
      apiKey: (configObj.apiKey || DEFAULT_AI_CONFIG.apiKey).trim()
    }
  } catch (error) {
    console.warn('获取AI配置失败，使用默认配置:', error)
    return DEFAULT_AI_CONFIG
  }
}

/**
 * 保存AI模型配置
 * @param {Object} config - AI配置对象
 * @returns {Promise<void>}
 */
export async function saveAiConfig(config) {
  try {
    // 清理配置数据，移除反引号和多余空格
    const cleanConfig = {
      apiUrl: (config.apiUrl || '').trim().replace(/[`]/g, ''),
      modelName: (config.modelName || '').trim(),
      apiKey: (config.apiKey || '').trim()
    }
    
    await storageAPI.setItem('aiModelConfig', cleanConfig)
  } catch (error) {
    console.error('保存AI配置失败:', error)
    throw error
  }
}

/**
 * 验证AI配置是否完整
 * @param {Object} config - AI配置对象
 * @returns {boolean} 是否配置完整
 */
export function validateAiConfig(config) {
  return !!(config && 
    config.apiUrl && config.apiUrl.trim() && 
    config.modelName && config.modelName.trim() && 
    config.apiKey && config.apiKey.trim())
}

/**
 * 获取可用模型列表
 * @param {Object} config - AI配置对象
 * @returns {Promise<Object>} 包含模型列表和状态的对象
 */
export async function getAvailableModels(config) {
  try {
    // 火山引擎常用模型列表（由于火山引擎没有直接的/v1/models接口，使用预定义列表）
    const volcEngineModels = [
      { id: 'doubao-seed-1-6-flash-250615', name: '豆包 1.6 Flash', available: true },
      { id: 'doubao-seed-1-6-thinking-250615', name: '豆包 1.6 Thinking', available: true },
      { id: 'doubao-seed-1-6-250615', name: '豆包 1.6', available: true },
      { id: 'doubao-pro-4k', name: '豆包 Pro 4K', available: true },
      { id: 'doubao-pro-32k', name: '豆包 Pro 32K', available: true },
      { id: 'doubao-pro-128k', name: '豆包 Pro 128K', available: true },
      { id: 'doubao-lite-4k', name: '豆包 Lite 4K', available: true },
      { id: 'doubao-lite-32k', name: '豆包 Lite 32K', available: true },
      { id: 'doubao-lite-128k', name: '豆包 Lite 128K', available: true }
    ]
    
    // 如果是火山引擎API，返回预定义模型列表
    if (config.apiUrl && config.apiUrl.includes('volces.com')) {
      return {
        success: true,
        models: volcEngineModels.filter(model => model.available),
        message: '模型列表获取成功'
      }
    }
    
    // 尝试调用OpenAI兼容的/v1/models接口
    const modelsUrl = config.apiUrl.replace('/chat/completions', '/models')
    const response = await fetch(modelsUrl, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${config.apiKey}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const data = await response.json()
      const availableModels = data.data?.filter(model => model.available !== false).map(model => ({
        id: model.id,
        name: model.id,
        available: true
      })) || []
      
      return {
        success: true,
        models: availableModels,
        message: '模型列表获取成功'
      }
    } else if (response.status === 404) {
      let errorData, errorMessage = '接口返回404错误'
      try {
        errorData = await response.json()
        if (errorData.error && errorData.error.message) {
          errorMessage = errorData.error.message
        }
      } catch (e) {
        errorData = await response.text()
      }
      return {
        success: false,
        models: [],
        message: errorMessage,
        error: errorData,
        faqUrl: 'https://www.ynaa.net/faq'
      }
    } else {
      let errorData, errorMessage = `获取模型列表失败: ${response.status}`
      try {
        errorData = await response.json()
        if (errorData.error && errorData.error.message) {
          errorMessage = errorData.error.message
        }
      } catch (e) {
        errorData = await response.text()
      }
      return {
        success: false,
        models: [{ id: config.modelName || 'gpt-3.5-turbo', name: config.modelName || 'gpt-3.5-turbo', available: true }],
        message: errorMessage,
        error: errorData
      }
    }
  } catch (error) {
    console.error('获取模型列表失败:', error)
    return {
      success: false,
      models: [{ id: config.modelName || 'gpt-3.5-turbo', name: config.modelName || 'gpt-3.5-turbo', available: true }],
      message: `网络错误: ${error.message}`,
      error: error.message
    }
  }
}

/**
 * 查询账户余额信息
 * @param {Object} config - AI配置对象
 * @returns {Promise<Object>} 余额信息
 */
export async function getAccountBalance(config) {
  try {
    // 火山引擎没有直接的余额查询API，通过测试调用来检查账户状态
    const response = await fetch(config.apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${config.apiKey}`
      },
      body: JSON.stringify({
        model: config.modelName,
        messages: [{
          role: 'user',
          content: '测试'
        }],
        max_tokens: 1
      })
    })

    if (response.ok) {
      const data = await response.json()
      // 从响应头或响应体中提取使用信息
      const usage = data.usage || {}
      return {
        status: 'success',
        message: '账户正常',
        usage: {
          prompt_tokens: usage.prompt_tokens || 0,
          completion_tokens: usage.completion_tokens || 0,
          total_tokens: usage.total_tokens || 0
        }
      }
    } else if (response.status === 404) {
      let errorData, errorMessage = '接口返回404错误'
      try {
        errorData = await response.json()
        if (errorData.error && errorData.error.message) {
          errorMessage = errorData.error.message
        }
      } catch (e) {
        errorData = await response.text()
      }
      return {
        status: 'error',
        message: errorMessage,
        error: errorData,
        faqUrl: 'https://www.ynaa.net/faq'
      }
    } else {
      let errorData, errorMessage = `账户异常: ${response.status}`
      try {
        errorData = await response.json()
        if (errorData.error && errorData.error.message) {
          errorMessage = errorData.error.message
        }
      } catch (e) {
        errorData = await response.text()
      }
      return {
        status: 'error',
        message: errorMessage,
        error: errorData
      }
    }
  } catch (error) {
    console.error('查询账户余额失败:', error)
    return {
      status: 'error',
      message: `查询失败: ${error.message}`,
      error: error.message
    }
  }
}